using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using Newtonsoft.Json;
using System.Configuration;

namespace demo
{
    /// <summary>
    /// 患者数据查询服务
    /// </summary>
    public class PatientDataService
    {
        // 统一的服务地址优化：以 BaseUrl + 相对路径 方式构建完整接口地址
        // BaseUrl 从 App.config 的 hisServiceUrl/hisUrl 读取，默认 http://10.1.200.169:82/
        private const string RedisQueryPath = "Redis/QueryRedisData";
        private const string DoctorPatientPath = "DoctorPatient/GetDoctorPatientRecords";
        private const string OutpApplyListPath = "His/QueryOutpApplyList";
        private const string OrderNameByApplyNoPath = "His/QueryOrderNameByApplyNoList";
        private const string ApplyInfoByDoctorCodeAndDaysPath = "His/QueryApplyInfoByDoctorCodeAndDays";
        private const string DoctorOutpDeptPermissionsPath = "His/QueryDoctorOutpDeptPermissions";
        private const string ReferralCardInfoPath = "His/QueryReferralCardInfo";
        private const string UpdateReferralCardExecInfoPath = "His/UpdateReferralCardExecInfo";

        private static string GetBaseUrl()
        {
            try
            {
                var url = ConfigurationManager.AppSettings["hisServiceUrl"];
                if (string.IsNullOrWhiteSpace(url))
                    url = ConfigurationManager.AppSettings["hisUrl"];
                if (string.IsNullOrWhiteSpace(url))
                    url = "http://10.1.200.169:82/";
                return NormalizeBaseUrl(url);
            }
            catch
            {
                return "http://10.1.200.169:82/";
            }
        }

        private static string NormalizeBaseUrl(string url)
        {
            if (string.IsNullOrWhiteSpace(url)) return "http://10.1.200.169:82/";
            return url.EndsWith("/") ? url : url + "/";
        }

        private static string BuildUrl(string relativePath)
        {
            if (string.IsNullOrWhiteSpace(relativePath)) return GetBaseUrl();
            if (relativePath.StartsWith("/")) relativePath = relativePath.Substring(1);
            return GetBaseUrl() + relativePath;
        }
        private const int TIMEOUT_MILLISECONDS = 30000;

        // ==== 转介卡 查询与更新 接口模型与方法 ====
        public class ReferralCardInfoItem
        {
            // 主键与患者维度
            [JsonProperty("card_info_id")] public string CardInfoId { get; set; }
            [JsonProperty("patient_id")] public string PatientId { get; set; }
            [JsonProperty("patient_visit_id")] public string PatientVisitId { get; set; }
            [JsonProperty("visit_id")] public string VisitId { get; set; }
            [JsonProperty("pati_name")] public string PatiName { get; set; }

            // 科室与医生（来源与接诊）
            [JsonProperty("org_source_code")] public string OrgSourceCode { get; set; }
            [JsonProperty("org_source_name")] public string OrgSourceName { get; set; }
            [JsonProperty("org_dest_code")] public string OrgDestCode { get; set; }
            [JsonProperty("org_dest_name")] public string OrgDestName { get; set; }
            [JsonProperty("emp_source_code")] public string EmpSourceCode { get; set; }
            [JsonProperty("emp_source_name")] public string EmpSourceName { get; set; }
            [JsonProperty("emp_dest_code")] public string EmpDestCode { get; set; }
            [JsonProperty("emp_dest_name")] public string EmpDestName { get; set; }

            // 执行信息
            [JsonProperty("emp_exec_code")] public string EmpExecCode { get; set; }
            [JsonProperty("emp_exec_name")] public string EmpExecName { get; set; }
            [JsonProperty("exec_date")] public string ExecDate { get; set; }

            // 申请/接诊时间
            [JsonProperty("source_date")] public string SourceDate { get; set; }
            [JsonProperty("dest_date")] public string DestDate { get; set; }

            // 状态与作废信息
            [JsonProperty("status")] public string Status { get; set; }
            [JsonProperty("invalidate")] public string Invalidate { get; set; }
            [JsonProperty("note")] public string Note { get; set; }
            [JsonProperty("emp_invali_code")] public string EmpInvaliCode { get; set; }
            [JsonProperty("emp_invali_name")] public string EmpInvaliName { get; set; }
            [JsonProperty("invali_datetime")] public string InvaliDatetime { get; set; }

            // 其他
            [JsonProperty("createdate")] public string CreateDate { get; set; }
            [JsonProperty("group_no")] public string GroupNo { get; set; }
        }

        public class ReferralCardInfoResponse
        {
            [JsonProperty("success")] public string Success { get; set; }
            [JsonProperty("msg")] public string Message { get; set; }
            [JsonProperty("data")] public List<ReferralCardInfoItem> Data { get; set; }
        }

        private class ReferralCardInfoRawResponse
        {
            [JsonProperty("success")] public string Success { get; set; }
            [JsonProperty("msg")] public string Message { get; set; }
            [JsonProperty("data")] public string Data { get; set; }
        }

        private class QueryReferralCardInfoRequest
        {
            [JsonProperty("start_time")] public string StartTime { get; set; }
            [JsonProperty("end_time")] public string EndTime { get; set; }
            [JsonProperty("org_source_code", NullValueHandling = NullValueHandling.Ignore)] public string OrgSourceCode { get; set; }
            [JsonProperty("org_dest_code", NullValueHandling = NullValueHandling.Ignore)] public string OrgDestCode { get; set; }
            [JsonProperty("emp_dest_code", NullValueHandling = NullValueHandling.Ignore)] public string EmpDestCode { get; set; }
        }

        public static ReferralCardInfoResponse QueryReferralCardInfo(string startTime, string endTime, string orgSourceCode = null, string orgDestCode = null, string empDestCode = null)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(startTime) || string.IsNullOrWhiteSpace(endTime))
                {
                    return new ReferralCardInfoResponse { Success = "0", Message = "开始/结束时间不能为空", Data = null };
                }

                var request = new QueryReferralCardInfoRequest
                {
                    StartTime = startTime,
                    EndTime = endTime,
                    OrgSourceCode = string.IsNullOrWhiteSpace(orgSourceCode) ? null : orgSourceCode,
                    OrgDestCode = string.IsNullOrWhiteSpace(orgDestCode) ? null : orgDestCode,
                    EmpDestCode = string.IsNullOrWhiteSpace(empDestCode) ? null : empDestCode
                };

                string jsonContent = JsonConvert.SerializeObject(request);
                Console.WriteLine($"转介卡查询请求URL: {BuildUrl(ReferralCardInfoPath)}");
                Console.WriteLine($"转介卡查询请求JSON: {jsonContent}");

                string responseContent = HttpPostJson(BuildUrl(ReferralCardInfoPath), jsonContent);
                Console.WriteLine($"转介卡查询响应内容: {responseContent}");

                if (string.IsNullOrEmpty(responseContent))
                {
                    return new ReferralCardInfoResponse { Success = "0", Message = "服务器无响应", Data = null };
                }

                var resp = JsonConvert.DeserializeObject<ReferralCardInfoResponse>(responseContent);
                if (resp != null && resp.Data != null)
                {
                    return resp;
                }

                var raw = JsonConvert.DeserializeObject<ReferralCardInfoRawResponse>(responseContent);
                if (raw != null)
                {
                    var items = new List<ReferralCardInfoItem>();
                    if (!string.IsNullOrWhiteSpace(raw.Data))
                    {
                        try
                        {
                            items = JsonConvert.DeserializeObject<List<ReferralCardInfoItem>>(raw.Data) ?? new List<ReferralCardInfoItem>();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"解析data为数组失败: {ex.Message}");
                        }
                    }
                    return new ReferralCardInfoResponse { Success = raw.Success, Message = raw.Message, Data = items };
                }

                return new ReferralCardInfoResponse { Success = "0", Message = "响应数据格式错误", Data = null };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"转介卡查询异常: {ex.Message}");
                return new ReferralCardInfoResponse { Success = "0", Message = string.Format("查询异常: {0}", ex.Message), Data = null };
            }
        }

        public class UpdateReferralCardExecInfoResponse
        {
            [JsonProperty("success")] public string Success { get; set; }
            [JsonProperty("msg")] public string Message { get; set; }
            [JsonProperty("data")] public string Data { get; set; }
        }

        private class UpdateReferralCardExecInfoRawResponse
        {
            [JsonProperty("success")] public string Success { get; set; }
            [JsonProperty("msg")] public string Message { get; set; }
            [JsonProperty("data")] public string Data { get; set; }
        }

        private class UpdateReferralCardExecInfoRequest
        {
            [JsonProperty("card_info_id")] public string CardInfoId { get; set; }
            [JsonProperty("emp_exec_code", NullValueHandling = NullValueHandling.Ignore)] public string EmpExecCode { get; set; }
            [JsonProperty("emp_exec_name", NullValueHandling = NullValueHandling.Ignore)] public string EmpExecName { get; set; }
            [JsonProperty("exec_date", NullValueHandling = NullValueHandling.Ignore)] public string ExecDate { get; set; }
            [JsonProperty("status", NullValueHandling = NullValueHandling.Ignore)] public string Status { get; set; }
            [JsonProperty("note", NullValueHandling = NullValueHandling.Ignore)] public string Note { get; set; }
        }

        public static UpdateReferralCardExecInfoResponse UpdateReferralCardExecInfo(
            string cardInfoId,
            string empExecCode = null,
            string empExecName = null,
            string execDate = null,
            string status = null,
            string note = null)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(cardInfoId))
                {
                    return new UpdateReferralCardExecInfoResponse { Success = "0", Message = "card_info_id不能为空", Data = "0" };
                }

                var request = new UpdateReferralCardExecInfoRequest
                {
                    CardInfoId = cardInfoId,
                    EmpExecCode = string.IsNullOrWhiteSpace(empExecCode) ? null : empExecCode,
                    EmpExecName = string.IsNullOrWhiteSpace(empExecName) ? null : empExecName,
                    ExecDate = string.IsNullOrWhiteSpace(execDate) ? null : execDate,
                    Status = string.IsNullOrWhiteSpace(status) ? null : status,
                    Note = string.IsNullOrWhiteSpace(note) ? null : note
                };

                string jsonContent = JsonConvert.SerializeObject(request);
                Console.WriteLine($"转介卡更新请求URL: {BuildUrl(UpdateReferralCardExecInfoPath)}");
                Console.WriteLine($"转介卡更新请求JSON: {jsonContent}");

                string responseContent = HttpPostJson(BuildUrl(UpdateReferralCardExecInfoPath), jsonContent);
                Console.WriteLine($"转介卡更新响应内容: {responseContent}");

                if (string.IsNullOrEmpty(responseContent))
                {
                    return new UpdateReferralCardExecInfoResponse { Success = "0", Message = "服务器无响应", Data = "0" };
                }

                var resp = JsonConvert.DeserializeObject<UpdateReferralCardExecInfoResponse>(responseContent);
                if (resp != null && resp.Success != null)
                {
                    return resp;
                }

                var raw = JsonConvert.DeserializeObject<UpdateReferralCardExecInfoRawResponse>(responseContent);
                if (raw != null)
                {
                    return new UpdateReferralCardExecInfoResponse { Success = raw.Success, Message = raw.Message, Data = raw.Data };
                }

                return new UpdateReferralCardExecInfoResponse { Success = "0", Message = "响应数据格式错误", Data = "0" };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"转介卡更新异常: {ex.Message}");
                return new UpdateReferralCardExecInfoResponse { Success = "0", Message = string.Format("更新异常: {0}", ex.Message), Data = "0" };
            }
        }

        // ==== 新接口：医生代码和时间查询申请单信息（入参出参见 doc/调用参数和返回值.md）====
        public class DoctorApplyInfoItem
        {
            [JsonProperty("apply_no")] public string ApplyNo { get; set; }
            [JsonProperty("order_name")] public string OrderName { get; set; }
            [JsonProperty("total_amount")] public decimal TotalAmount { get; set; }
            [JsonProperty("create_date")] public string CreateDate { get; set; }
            [JsonProperty("apply_type_name")] public string ApplyTypeName { get; set; }
            [JsonProperty("patient_id")] public string PatientId { get; set; }
            [JsonProperty("order_doc")] public string OrderDoc { get; set; }
            [JsonProperty("visit_id")] public string VisitId { get; set; }
            [JsonProperty("patient_visit_id")] public string PatientVisitId { get; set; }
            [JsonProperty("order_doc_code")] public string OrderDocCode { get; set; }
        }

        public class DoctorApplyInfoResponse
        {
            [JsonProperty("success")] public string Success { get; set; }
            [JsonProperty("msg")] public string Message { get; set; }
            [JsonProperty("data")] public List<DoctorApplyInfoItem> Data { get; set; }
        }

        // 兼容数据字段为字符串(JSON数组字符串)的返回结构
        private class DoctorApplyInfoRawResponse
        {
            [JsonProperty("success")] public string Success { get; set; }
            [JsonProperty("msg")] public string Message { get; set; }
            [JsonProperty("data")] public string Data { get; set; }
        }

        private class DoctorApplyInfoTimeRangeRequest
        {
            [JsonProperty("start_time")] public string StartTime { get; set; }
            [JsonProperty("end_time")] public string EndTime { get; set; }
            [JsonProperty("patient_id")] public string OrderDocCode { get; set; }
        }

        private class DoctorApplyInfoDaysRequest
        {
            [JsonProperty("days")] public int Days { get; set; }
            [JsonProperty("patient_id")] public string patient_id { get; set; }
        }

        // ==== 门诊医生所在门诊科室权限查询 ====
        public class DoctorOutpDeptPermissionItem
        {
            [JsonProperty("ROLE_NAME")] public string RoleName { get; set; }
            [JsonProperty("ORG_CODE")] public string OrgCode { get; set; }
            [JsonProperty("DEPT_NAME")] public string DeptName { get; set; }
            [JsonProperty("DOCTOR_NAME")] public string DoctorName { get; set; }
            [JsonProperty("USER_NAME")] public string UserName { get; set; }
            [JsonProperty("ORG_SOURCE_CODE")] public string OrgSourceCode { get; set; }
            [JsonProperty("ORG_SOURCE_NAME")] public string OrgSourceName { get; set; }
        }

        public class DoctorOutpDeptPermissionsResponse
        {
            [JsonProperty("success")] public string Success { get; set; }
            [JsonProperty("msg")] public string Message { get; set; }
            [JsonProperty("data")] public List<DoctorOutpDeptPermissionItem> Data { get; set; }
        }

        private class DoctorOutpDeptPermissionsRawResponse
        {
            [JsonProperty("success")] public string Success { get; set; }
            [JsonProperty("msg")] public string Message { get; set; }
            [JsonProperty("data")] public string Data { get; set; }
        }

        private class DoctorOutpDeptPermissionsRequest
        {
            [JsonProperty("user_name")] public string UserName { get; set; }
        }

        /// <summary>
        /// 查询患者数据
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>患者数据查询结果</returns>
        public static PatientDataResponse QueryPatientData(string userId)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(userId))
                {
                    return new PatientDataResponse
                    {
                        Success = false,
                        Message = "用户ID不能为空",
                        Data = null
                    };
                }

                // 创建请求对象
                var request = new PatientDataRequest
                {
                    UserId = userId
                };

                // 序列化请求数据
                string jsonContent = JsonConvert.SerializeObject(request);
                
                // 发送POST请求
                string responseContent = HttpPostJson(BuildUrl(RedisQueryPath), jsonContent);
                
                if (string.IsNullOrEmpty(responseContent))
                {
                    return new PatientDataResponse
                    {
                        Success = false,
                        Message = "服务器无响应",
                        Data = null
                    };
                }

                // 反序列化响应数据
                var result = JsonConvert.DeserializeObject<PatientDataResponse>(responseContent);
                return result ?? new PatientDataResponse
                {
                    Success = false,
                    Message = "响应数据格式错误",
                    Data = null
                };
            }
            catch (Exception ex)
            {
                return new PatientDataResponse
                {
                    Success = false,
                    Message = string.Format("查询异常: {0}", ex.Message),
                    Data = null
                };
            }
        }


        /// <summary>
        /// 获取医生患者记录数据
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>患者数据查询结果</returns>
        public static DoctorPatientRecordsResponse GetDoctorPatientRecords(string userId)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(userId))
                {
                    return new DoctorPatientRecordsResponse
                    {
                        Success = false,
                        Message = "用户ID不能为空",
                        Data = null
                    };
                }

                // 创建请求对象
                var request = new PatientDataRequest
                {
                    UserId = userId
                };

                // 序列化请求数据
                string jsonContent = JsonConvert.SerializeObject(request);
                
                // 发送POST请求
                string responseContent = HttpPostJson(BuildUrl(DoctorPatientPath), jsonContent);
                
                if (string.IsNullOrEmpty(responseContent))
                {
                    return new DoctorPatientRecordsResponse
                    {
                        Success = false,
                        Message = "服务器无响应",
                        Data = null
                    };
                }

                // 反序列化响应数据
                var result = JsonConvert.DeserializeObject<DoctorPatientRecordsResponse>(responseContent);
                return result ?? new DoctorPatientRecordsResponse
                {
                    Success = false,
                    Message = "响应数据格式错误",
                    Data = null
                };
            }
            catch (Exception ex)
            {
                return new DoctorPatientRecordsResponse
                {
                    Success = false,
                    Message = string.Format("查询异常: {0}", ex.Message),
                    Data = null
                };
            }
        }

        /// <summary>
        /// 查询患者申请单
        /// </summary>
        /// <param name="patientId">患者ID</param>
        /// <param name="days">查询最近几天的数据，默认10天</param>
        /// <returns>患者申请单查询结果</returns>
        public static PatientApplyListResponse QueryOutpApplyList(string patientId, int days = 10)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(patientId))
                {
                    return new PatientApplyListResponse
                    {
                        Success = "0",
                        Message = "患者ID不能为空",
                        Data = null
                    };
                }

                // 创建请求对象
                var request = new PatientApplyListRequest
                {
                    PatientId = patientId,
                    Days = days
                };

                // 序列化请求数据
                string jsonContent = JsonConvert.SerializeObject(request);
                
                // 记录调试信息
                Console.WriteLine($"查询患者申请单请求URL: {BuildUrl(OutpApplyListPath)}");
                Console.WriteLine($"查询患者申请单请求JSON: {jsonContent}");
                
                // 发送POST请求
                string responseContent = HttpPostJson(BuildUrl(OutpApplyListPath), jsonContent);
                
                // 记录调试信息
                Console.WriteLine($"查询患者申请单响应内容: {responseContent}");
                
                if (string.IsNullOrEmpty(responseContent))
                {
                    return new PatientApplyListResponse
                    {
                        Success = "0",
                        Message = "服务器无响应",
                        Data = null
                    };
                }

                // 反序列化响应数据
                var result = JsonConvert.DeserializeObject<PatientApplyListResponse>(responseContent);
                return result ?? new PatientApplyListResponse
                {
                    Success = "0",
                    Message = "响应数据格式错误",
                    Data = null
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"查询患者申请单异常: {ex.Message}");
                return new PatientApplyListResponse
                {
                    Success = "0",
                    Message = string.Format("查询异常: {0}", ex.Message),
                    Data = null
                };
            }
        }

        /// <summary>
        /// 根据申请单号查询医嘱名称
        /// </summary>
        /// <param name="applyNos">申请单号数组</param>
        /// <returns>医嘱名称查询结果</returns>
        public static QueryOrderNameByApplyNoResponse QueryOrderNameByApplyNoList(string[] applyNos)
        {
            try
            {
                if (applyNos == null || applyNos.Length == 0)
                {
                    return new QueryOrderNameByApplyNoResponse
                    {
                        Success = "0",
                        Message = "申请单号不能为空",
                        Data = null
                    };
                }

                // 创建请求对象
                var request = new QueryOrderNameByApplyNoRequest
                {
                    ApplyNos = applyNos
                };

                // 序列化请求数据
                string jsonContent = JsonConvert.SerializeObject(request);
                
                // 记录调试信息
                Console.WriteLine($"查询医嘱名称请求URL: {BuildUrl(OrderNameByApplyNoPath)}");
                Console.WriteLine($"查询医嘱名称请求JSON: {jsonContent}");
                
                // 发送POST请求
                string responseContent = HttpPostJson(BuildUrl(OrderNameByApplyNoPath), jsonContent);
                
                // 记录调试信息
                Console.WriteLine($"查询医嘱名称响应内容: {responseContent}");
                
                if (string.IsNullOrEmpty(responseContent))
                {
                    return new QueryOrderNameByApplyNoResponse
                    {
                        Success = "0",
                        Message = "服务器无响应",
                        Data = null
                    };
                }

                // 反序列化响应数据
                var result = JsonConvert.DeserializeObject<QueryOrderNameByApplyNoResponse>(responseContent);
                return result ?? new QueryOrderNameByApplyNoResponse
                {
                    Success = "0",
                    Message = "响应数据格式错误",
                    Data = null
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"查询医嘱名称异常: {ex.Message}");
                return new QueryOrderNameByApplyNoResponse
                {
                    Success = "0",
                    Message = string.Format("查询异常: {0}", ex.Message),
                    Data = null
                };
            }
        }

        /// <summary>
        /// 根据申请单号查询医嘱名称（单个申请单号）
        /// </summary>
        /// <param name="applyNo">申请单号</param>
        /// <returns>医嘱名称查询结果</returns>
        public static QueryOrderNameByApplyNoResponse QueryOrderNameByApplyNo(string applyNo)
        {
            if (string.IsNullOrWhiteSpace(applyNo))
            {
                return new QueryOrderNameByApplyNoResponse
                {
                    Success = "0",
                    Message = "申请单号不能为空",
                    Data = null
                };
            }

            return QueryOrderNameByApplyNoList(new string[] { applyNo });
        }

        /// <summary>
        /// 门诊医生所在门诊科室权限查询
        /// 路径参考：doc/门诊医生科室权限查询接口文档.md
        /// </summary>
        /// <param name="userName">医生账户名（HIS登录账户）</param>
        /// <returns>权限查询结果</returns>
        public static DoctorOutpDeptPermissionsResponse QueryDoctorOutpDeptPermissions(string userName)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(userName))
                {
                    return new DoctorOutpDeptPermissionsResponse
                    {
                        Success = "0",
                        Message = "医生账户名不能为空",
                        Data = null
                    };
                }

                var request = new DoctorOutpDeptPermissionsRequest { UserName = userName };
                string jsonContent = JsonConvert.SerializeObject(request);

                Console.WriteLine($"门诊医生科室权限查询请求URL: {BuildUrl(DoctorOutpDeptPermissionsPath)}");
                Console.WriteLine($"门诊医生科室权限查询请求JSON: {jsonContent}");

                string responseContent = HttpPostJson(BuildUrl(DoctorOutpDeptPermissionsPath), jsonContent);
                Console.WriteLine($"门诊医生科室权限查询响应内容: {responseContent}");

                if (string.IsNullOrEmpty(responseContent))
                {
                    return new DoctorOutpDeptPermissionsResponse
                    {
                        Success = "0",
                        Message = "服务器无响应",
                        Data = null
                    };
                }

                // 优先按标准结构(数组)解析
                var resp = JsonConvert.DeserializeObject<DoctorOutpDeptPermissionsResponse>(responseContent);
                if (resp != null && resp.Data != null)
                {
                    return resp;
                }

                // 兼容 data 为字符串(JSON数组字符串)的返回
                var raw = JsonConvert.DeserializeObject<DoctorOutpDeptPermissionsRawResponse>(responseContent);
                if (raw != null)
                {
                    var items = new List<DoctorOutpDeptPermissionItem>();
                    if (!string.IsNullOrWhiteSpace(raw.Data))
                    {
                        try
                        {
                            items = JsonConvert.DeserializeObject<List<DoctorOutpDeptPermissionItem>>(raw.Data) ?? new List<DoctorOutpDeptPermissionItem>();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"解析data为数组失败: {ex.Message}");
                        }
                    }
                    return new DoctorOutpDeptPermissionsResponse { Success = raw.Success, Message = raw.Message, Data = items };
                }

                return new DoctorOutpDeptPermissionsResponse { Success = "0", Message = "响应数据格式错误", Data = null };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"门诊医生科室权限查询异常: {ex.Message}");
                return new DoctorOutpDeptPermissionsResponse { Success = "0", Message = string.Format("查询异常: {0}", ex.Message), Data = null };
            }
        }

        /// <summary>
        /// 通过医生代码和时间范围查询申请单信息（时间范围优先）
        /// 入参出参参考：doc/调用参数和返回值.md
        /// </summary>
        /// <param name="orderDocCode">医生代码</param>
        /// <param name="startTime">开始时间(yyyy-MM-dd HH:mm:ss)</param>
        /// <param name="endTime">结束时间(yyyy-MM-dd HH:mm:ss)</param>
        /// <returns>查询结果</returns>
        public static DoctorApplyInfoResponse QueryApplyInfoByDoctorCodeAndTimeRange(string orderDocCode, string startTime, string endTime)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(orderDocCode))
                {
                    return new DoctorApplyInfoResponse { Success = "0", Message = "医生代码不能为空", Data = null };
                }
                if (string.IsNullOrWhiteSpace(startTime) || string.IsNullOrWhiteSpace(endTime))
                {
                    return new DoctorApplyInfoResponse { Success = "0", Message = "开始时间/结束时间不能为空", Data = null };
                }

                var request = new DoctorApplyInfoTimeRangeRequest
                {
                    OrderDocCode = orderDocCode,
                    StartTime = startTime,
                    EndTime = endTime
                };

                string jsonContent = JsonConvert.SerializeObject(request);
                Console.WriteLine($"医生代码和时间查询请求URL: {BuildUrl(ApplyInfoByDoctorCodeAndDaysPath)}");
                Console.WriteLine($"医生代码和时间查询请求JSON: {jsonContent}");

                string responseContent = HttpPostJson(BuildUrl(ApplyInfoByDoctorCodeAndDaysPath), jsonContent);
                Console.WriteLine($"医生代码和时间查询响应内容: {responseContent}");

                if (string.IsNullOrEmpty(responseContent))
                {
                    return new DoctorApplyInfoResponse { Success = "0", Message = "服务器无响应", Data = null };
                }

                // 先按标准结构(数组)解析
                var resp = JsonConvert.DeserializeObject<DoctorApplyInfoResponse>(responseContent);
                if (resp != null && resp.Data != null)
                {
                    return resp;
                }

                // 兼容 data 为字符串(JSON数组字符串)的返回
                var raw = JsonConvert.DeserializeObject<DoctorApplyInfoRawResponse>(responseContent);
                if (raw != null)
                {
                    var items = new List<DoctorApplyInfoItem>();
                    if (!string.IsNullOrWhiteSpace(raw.Data))
                    {
                        try
                        {
                            items = JsonConvert.DeserializeObject<List<DoctorApplyInfoItem>>(raw.Data) ?? new List<DoctorApplyInfoItem>();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"解析data为数组失败: {ex.Message}");
                        }
                    }
                    return new DoctorApplyInfoResponse { Success = raw.Success, Message = raw.Message, Data = items };
                }

                return new DoctorApplyInfoResponse { Success = "0", Message = "响应数据格式错误", Data = null };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"医生代码和时间查询异常: {ex.Message}");
                return new DoctorApplyInfoResponse { Success = "0", Message = string.Format("查询异常: {0}", ex.Message), Data = null };
            }
        }

        /// <summary>
        /// 通过患者ID和天数查询申请单信息（当未提供时间范围时可使用）
        /// 入参出参参考：doc/调用参数和返回值.md
        /// </summary>
        /// <param name="orderDocCode">医生代码</param>
        /// <param name="days">查询天数(正整数，最大365)</param>
        /// <returns>查询结果</returns>
        public static DoctorApplyInfoResponse QueryApplyInfoByDoctorCodeAndDays(string patient_id, int days)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(patient_id))
                {
                    return new DoctorApplyInfoResponse { Success = "0", Message = "医生代码不能为空", Data = null };
                }
                if (days <= 0 || days > 365)
                {
                    return new DoctorApplyInfoResponse { Success = "0", Message = "天数需为1-365之间的正整数", Data = null };
                }

                var request = new DoctorApplyInfoDaysRequest
                {
                    patient_id = patient_id,
                    Days = days
                };

                string jsonContent = JsonConvert.SerializeObject(request);
                Console.WriteLine($"医生代码和天数查询请求URL: {BuildUrl(ApplyInfoByDoctorCodeAndDaysPath)}");
                Console.WriteLine($"医生代码和天数查询请求JSON: {jsonContent}");

                string responseContent = HttpPostJson(BuildUrl(ApplyInfoByDoctorCodeAndDaysPath), jsonContent);
                Console.WriteLine($"医生代码和天数查询响应内容: {responseContent}");

                if (string.IsNullOrEmpty(responseContent))
                {
                    return new DoctorApplyInfoResponse { Success = "0", Message = "服务器无响应", Data = null };
                }

                var resp = JsonConvert.DeserializeObject<DoctorApplyInfoResponse>(responseContent);
                if (resp != null && resp.Data != null)
                {
                    return resp;
                }

                var raw = JsonConvert.DeserializeObject<DoctorApplyInfoRawResponse>(responseContent);
                if (raw != null)
                {
                    var items = new List<DoctorApplyInfoItem>();
                    if (!string.IsNullOrWhiteSpace(raw.Data))
                    {
                        try
                        {
                            items = JsonConvert.DeserializeObject<List<DoctorApplyInfoItem>>(raw.Data) ?? new List<DoctorApplyInfoItem>();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"解析data为数组失败: {ex.Message}");
                        }
                    }
                    return new DoctorApplyInfoResponse { Success = raw.Success, Message = raw.Message, Data = items };
                }

                return new DoctorApplyInfoResponse { Success = "0", Message = "响应数据格式错误", Data = null };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"医生代码和天数查询异常: {ex.Message}");
                return new DoctorApplyInfoResponse { Success = "0", Message = string.Format("查询异常: {0}", ex.Message), Data = null };
            }
        }
        /// <summary>
        /// HTTP POST JSON请求方法
        /// </summary>
        /// <param name="Url">请求URL</param>
        /// <param name="paramData">JSON参数数据</param>
        /// <param name="headerDic">请求头字典</param>
        /// <param name="Method">请求方法</param>
        /// <returns>响应JSON字符串</returns>
        private static string HttpPostJson(string Url, string paramData, Dictionary<string, string> headerDic = null, string Method = "POST")
        {
            string jsons;
            try
            {
                HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(Url);
                wbRequest.KeepAlive = false;
                wbRequest.Method = Method;
                wbRequest.ContentType = "application/json";
                wbRequest.ContentLength = Encoding.UTF8.GetByteCount(paramData);
                if (headerDic != null && headerDic.Count > 0)
                {
                    foreach (var item in headerDic)
                    {
                        wbRequest.Headers.Add(item.Key, item.Value);
                    }
                }
                using (Stream requestStream = wbRequest.GetRequestStream())
                {
                    using (StreamWriter swrite = new StreamWriter(requestStream))
                    {
                        swrite.Write(paramData);
                    }
                }
                HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
                using (Stream responseStream = wbResponse.GetResponseStream())
                {
                    using (StreamReader sread = new StreamReader(responseStream))
                    {
                        jsons = sread.ReadToEnd();
                    }
                }
            }
            catch
            {
                return "";
            }
            return jsons;
        }
    }
}